
/***
 * 执行 dart run build_runner build 生成.g.dart文件
 */

import 'dart:convert';


import 'package:json_annotation/json_annotation.dart';

import '../../../common_code/models/base_model.dart';
import '../../../common_code/wrapper/shared_preferences_wrapper/shared_preferences_wrapper.dart';

part 'login_model.g.dart';

@JsonSerializable(explicitToJson: true)
class LoginModel extends BaseModel {
  LoginModelData? data;

  LoginModel({required super.errorCode, required super.errorMsg, required this.data});

  factory LoginModel.fromJson(Map<String, dynamic> json) =>
      _$LoginModelFromJson(json);

  @override
  Map<String, dynamic> toJson() => _$LoginModelToJson(this);
}

@JsonSerializable()
class LoginModelData {
  static const String spfKey = 'loginModel';
  late String token;
  late String username;

  LoginModelData({required this.token, required this.username});


  factory LoginModelData.fromJson(Map<String, dynamic> json) =>
      _$LoginModelDataFromJson(json);

  Map<String, dynamic> toJson() => _$LoginModelDataToJson(this);

  // 保存登录数据
  void save() {
    SharedPreferencesWrapper.setString(spfKey, jsonEncode(toJson()));
  }

  // 加载登录数据
  static LoginModelData? loadCacheData() {
    var json = SharedPreferencesWrapper.getString(spfKey);
    if (json != null) {
      // 使用 jsonDecode 函数将标准 JSON 字符串转换为 Map
      Map<String, dynamic> resultMap = jsonDecode(json);
      return LoginModelData.fromJson(resultMap);
    }
    return null;
  }

  // 清除登录数据
  static void clearCacheData() {
    SharedPreferencesWrapper.remove(spfKey);
  }
}
